<template>
  <div class="aui-wrapper aui-page__share">
    <div class="aui-content__wrapper">
      <template>
        <div class="share-title">{{ $t('brand.lg') }}</div>
        <div class="share-password-body" v-if="!isAllow">
          <div class="main-password-content" style="padding-bottom: 20px">
            <template v-if="isFile404">
              <div style="text-align: center;">
                <div style="margin-bottom: 15px;">
                  <img style="width: 74px;height: 70px;" src="~@/assets/img/errorImg.png">
                </div>
                <span style="color: #424e67;font-size: 14px;font-weight: 200;">啊哦，你来晚了，分享的文件已经被取消了，下次要早点哟。</span>
              </div>
            </template>
            <template v-if="!isFile404">
              <div style="padding: 0 0 5px;margin: 20px 0 10px;">请输入提取码：</div>
              <div>
                <el-input v-model="dataForm.password" placeholder="请输入提取码" style="display: inline-block;width: calc(100% - 120px)"></el-input>
                <el-button type="primary" style="display: inline-block;margin-left: 10px" @click="submitPassword()">提取文件</el-button>
                <div style="color: red;margin-top: 10px;margin-bottom: 10px" v-if="dataForm.passwordErrorMsg">{{dataForm.passwordErrorMsg}}</div>
              </div>
            </template>
          </div>
        </div>
        <div class="share-file-body" v-if="isAllow && !isFile404" style="padding-bottom: 20px">
          <div class="file-info">
            <div class="filename" :title="fileData.fileName">{{fileData.fileName}}</div>
            <div class="desc">
              {{fileData.createDate}}
              (有效期:{{fileData.expireDay==-1?'永久':fileData.expireDay}}
              <template v-if="fileData.expireDay && fileData.expireDay!=-1">天</template>)
            </div>
          </div>
          <div style="float: right">
            <el-button size="medium" v-if="curUser.username==fileData.userName" @click="removeShare(fileData.sign)" style="margin-top: 10px">取消分享</el-button>
            <el-button size="medium" @click="downloadFile(fileData.sign)">下载<template v-if="fileData.size">({{ bytesToSize(fileData.size) }})</template></el-button>
          </div>
        </div>
        <div class="cloud-bg">
          <div class="bg_end" style="background: url('./static/img/share-bg.png');"></div>
        </div>
      </template>
    </div>
  </div>
</template>

<script>
import Cookies from 'js-cookie'
import debounce from 'lodash/debounce'
import numberUtils from '@/utils/NumberUtils.js' // 计算相关工具
export default {
  data () {
    return {
      dataForm: {
        password: '',
        passwordErrorMsg: ''
      },
      curUser: {},
      // 文件是否取消
      isFile404: false,
      // 是否允许下载
      isAllow: false,
      fileData: {

      }
    }
  },
  computed: {
    dataRule () {
      return {
        username: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        password: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        captcha: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ]
      }
    },
    formatTow () {
      return (price) => {
        price = price + ''
        const pointIndex = price.indexOf('.')
        if (pointIndex !== -1) {
          return price.substring(0, pointIndex + 3)
        } else {
          return price
        }
      }
    },
    bytesToSize () {
      return (bytes) => {
        let temp = bytes
        let units = ''
        if (bytes < 1024) {
          units = 'B'
        } else if (bytes < (1024 * 1024)) {
          temp = numberUtils.divide(bytes, 1024)
          units = 'KB'
        } else if (bytes < (1024 * 1024 * 1024)) {
          temp = numberUtils.divide(bytes, (1024 * 1024))
          units = 'MB'
        } else {
          temp = numberUtils.divide(bytes, (1024 * 1024 * 1024))
          units = 'GB'
        }
        return this.formatTow(temp) + units
      }
    }
  },
  created () {
    this.getInfo(this.$route.query.sign)
  },
  watch: {
    // 或者
    $route () {
      if (this.$route.query.sign) {
        // 重新加载一次created或者mounted钩子中的渲染的数据
        window.location.reload()
      }
    }
  },
  methods: {
    downloadFile (sign) {
      if (!sign) {
        this.dataForm.passwordErrorMsg = '缺少参数'
        return
      }
      const downloadUrl = `${window.SITE_CONFIG.apiURL}/api/oss/download?sign=${sign}`
      location.href = downloadUrl
    },
    // 获取验证码
    getInfo (sign) {
      if (!sign) {
        this.dataForm.passwordErrorMsg = '缺少参数'
        return
      }
      this.$http.get(`/api/oss/getInfo/${sign || ''}`, this.dataForm).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.fileData = {
          ...res.data
        }

        if (this.fileData.sign && this.fileData.fileExists) {
          this.isFile404 = false

          this.curUser = res.otherData || {}
          const password = Cookies.get(window.SITE_CONFIG.$config.tokenKeySign + '-share-' + this.fileData.sign) || ''
          if (this.fileData.password === password) {
            this.isAllow = true
          }
        } else {
          this.isFile404 = true
          this.isAllow = false
        }
      }).catch(() => {})
    },
    removeShare (sign) {
      if (!sign) {
        this.dataForm.passwordErrorMsg = '缺少参数'
        return
      }
      this.$confirm('是否确定取消分享?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0)'
        })
        this.$http.post(`/oss/share/remove/${sign || ''}`).then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          window.location.reload()
        }).catch(() => {
          loading.close()
        })
      }).catch(() => {})
    },
    // 提交提取码
    submitPassword: debounce(function () {
      if (!this.dataForm.password) {
        this.dataForm.passwordErrorMsg = '请输入提取码'
      } else {
        this.dataForm.passwordErrorMsg = ''
      }
      if (this.fileData.password === this.dataForm.password) {
        Cookies.set(window.SITE_CONFIG.$config.tokenKeySign + '-share-' + this.fileData.sign, this.fileData.password)
        this.isAllow = true
      } else {
        this.dataForm.passwordErrorMsg = '提取码错误'
      }
    }, 200, { leading: true, trailing: false })
  }
}
</script>
<style scoped>
page{
  background: #f7f7f7;
}
.aui-page__share .share-title{
  font-size: 40px;
  font-weight: 400;
  position: absolute;
  top: 25%;
  left: 50%;
  transform: translateX(-50%);
  font-family: PingFangSC-Semibold;
}
.aui-page__share .share-password-body,.aui-page__share .share-file-body{
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-70%);
}
.aui-page__share .share-password-body .main-password-content,.aui-page__share .share-file-body{
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 0 10px rgb(171 198 235 / 30%);
  width: 460px;
  padding: 20px 30px 48px;
}
.aui-page__share .el-button--primary{
  border: 1px solid #09AAFF;
  background: #09AAFF;
}

.aui-page__share .el-button--primary:hover{
  border: 1px solid #0098EA;
  background: #0098EA;
}
.aui-page__share .cloud-bg{
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 400px;
}
.aui-page__share .bg_end{
  position: absolute;
  width: 100%;
  height: 400px;
  background-repeat: repeat-x !important;
  background-position: 0 bottom !important;
  bottom: 0;
}

/*文件信息*/
.aui-page__share .share-file-body .file-info{
  display: inline-block;
}
.aui-page__share .share-file-body .file-info .filename{
  color: #424e67;
  font-size: 14px;
  font-weight: 200;
  line-height: 32px;
  width: 180px;
  overflow: hidden;
  text-overflow: ellipsis;
}
.aui-page__share .share-file-body .file-info .desc{
}

</style>
